package com.sczmgk.track.activity;

import android.os.Bundle;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.InputType;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.sczmgk.track.MyApp;
import com.sczmgk.track.R;
import com.sczmgk.track.activity.trackactivity.TracingActivity;
import com.sczmgk.track.base.CheckPermissionBaseActivity;
import com.sczmgk.track.constant.Constant;
import com.sczmgk.track.db.impl.UserDaoImpl;
import com.sczmgk.track.dialog.DialogFactory;
import com.sczmgk.track.dialog.MessageDialog;
import com.sczmgk.track.entity.User;
import com.sczmgk.track.entity.bean.UserData;
import com.sczmgk.track.httpUtils.MyHttp;
import com.sczmgk.track.test.MyCallback;
import com.sczmgk.track.utils.CacheUtils;
import com.sczmgk.track.utils.CommonUtils;
import com.sczmgk.track.utils.MyLog;
import com.sczmgk.track.utils.MyToast;
import com.sczmgk.track.utils.Tools;
import com.sczmgk.track.utils.UIUtils;
import com.sczmgk.track.view.LoginDeleteItemView;

import java.util.HashMap;
import java.util.Map;

import static com.sczmgk.track.constant.Constant.DEVICE_NOT_ACTIVE;
import static com.sczmgk.track.constant.Constant.managerPhone;

/**
 * Created by Administrator on 2017/9/25.
 */
public class LoginActivity extends CheckPermissionBaseActivity {

    //密码
    private LoginDeleteItemView mPwd;

    //工号
    private LoginDeleteItemView mJobNum;

    //工号的容器
    private LinearLayout mLayoutJobNum;
    private CheckBox mCbShowPassword;
    private TextView mTvForgetPwd;

    private MessageDialog callPhoneDialg;

    @Override
    public void handleMessage(Message msg) {

    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        View decorView = getWindow().getDecorView();
        decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN);

        goneHeadView();

        //密码
        mPwd = (LoginDeleteItemView) findViewById(R.id.cdi_login_pwd);

        //工号
        mJobNum = (LoginDeleteItemView) findViewById(R.id.cdi_login_job_number);

        //工号的容器
        mLayoutJobNum = (LinearLayout) findViewById(R.id.ll_login_job_num_container);

        //展示密码
        mCbShowPassword = (CheckBox) findViewById(R.id.cb_login_show_password);

        //忘记密码
        mTvForgetPwd = (TextView) findViewById(R.id.tv_login_forget_pwd);

        mPwd.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);

        initData();

        setListener();
    }

    private void setListener() {
        //显示密码
        mCbShowPassword.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
                if (isChecked) {
                    //显示密码
                    mPwd.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                } else {
                    //隐藏密码
                    mPwd.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                }
                //光标定在最后一位
                String password = mPwd.getText();
                if (!TextUtils.isEmpty(password)) {
                    mPwd.setSelection(password.length());
                }
            }
        });

        //忘记密码
        mTvForgetPwd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (callPhoneDialg == null) {
                    showCallPhoneDialog();
                } else if (!callPhoneDialg.isShowing()) {
                    showCallPhoneDialog();
                }
            }
        });
    }

    private void showCallPhoneDialog() {
        callPhoneDialg = DialogFactory.chooseDialog(LoginActivity.this, getResources().getString(R.string.call_phone_des) + managerPhone, getResources().getString(R.string.sure), new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                checkPhone(managerPhone);
            }
        });
    }

    private void initData() {
        //TODO 是否已缓存工号 如果缓存了工号则设置 且输入框不可输入变灰
//        String jobNum = CacheUtils.getJobNum(LoginActivity.this);
//        User user = UserDaoImpl.getLoginUser(LoginActivity.this);
//        if (user != null || !Tools.isEmpty(user.worknumber)){
//            mJobNum.setText(user.worknumber);
//            mJobNum.setFocusable(false);
//            mJobNum.setClickable(false);
//        }else{
//            mJobNum.setFocusable(true);
//            mJobNum.setClickable(true);
//        }
    }

    public void loginClick(View view) {
        //检查手机权限
        checkPhone("");
    }

    private void parseJson(User user) {
        //设置登录状态
        CacheUtils.cacheLoginStatus(LoginActivity.this,true);
        MyApp.loginUserUid = user.userid;
        MyApp.loginUserName = user.username;
        CacheUtils.setLoginUserid(LoginActivity.this, user.userid);
        CacheUtils.cacheLoginStatus(LoginActivity.this, true);
//        CacheUtils.setJobNum(LoginActivity.this,user.worknumber);
        //存入数据库
        if (UserDaoImpl.isExists(LoginActivity.this, user.userid)) {
            User oldUser = UserDaoImpl.findByUid(LoginActivity.this, user.userid);
            user.setId(oldUser.getId());
            user.imageLocalPath = oldUser.imageLocalPath;
            UserDaoImpl.getIntance(LoginActivity.this).updata(user);
        } else {
            UserDaoImpl.getIntance(LoginActivity.this).insert(user);
        }

        if (user.imeistatus != DEVICE_NOT_ACTIVE) {
            UIUtils.startActivity(LoginActivity.this, TracingActivity.class);
        }else{
            UIUtils.startActivity(LoginActivity.this, DeviceActiveActivity.class);
        }
        finish();
    }

    @Override
    public boolean getIsNeedLogin() {
        return false;
    }

    @Override
    public void onSelectedPhonePermission(String phoneNumber) {
        if (Tools.isEmpty(phoneNumber)){
            login();
        }else{
            CommonUtils.callPhone(LoginActivity.this ,phoneNumber);
        }
    }

    private void login() {
        //TODO 测试
//        UIUtils.startActivity(LoginActivity.this, TracingActivity.class);
//        finish();

        //输入的工号
        String inputJobNum = mJobNum.getText();

        //输入的密码
        String inputPwd = mPwd.getText();

        if (Tools.isEmpty(inputJobNum)) {
            MyToast.show(LoginActivity.this, "请输入您的工号");
            return;
        }

        if (Tools.isEmpty(inputPwd)) {
            MyToast.show(LoginActivity.this, "请输入您的密码");
            return;
        }

        Map<String, Object> dataMaps = new HashMap<>();
        dataMaps.put("worknumber", inputJobNum);
        dataMaps.put("password", inputPwd);
        dataMaps.put("imei", MyApp.imei);

        showLoadingDiaLog();


        MyHttp.requestDataT(LoginActivity.this, Constant.LOGIN_URL, MyHttp.POST, null, dataMaps, null, false, null, new MyCallback<UserData>() {
            @Override
            public void onSuccess(UserData o) {
                try {
                    parseJson(o.data);
                } catch (Exception e) {
                    e.printStackTrace();
                    MyLog.e(TAG,"Json解析错误");
                }
            }

            @Override
            public void onUnknownError() {
                dismissLoadingDiaLog();
            }

            @Override
            public void onError(String msg) {
                dismissLoadingDiaLog();
                showErrorMsg(msg);
            }

            @Override
            public void onSuccess() {

            }
        });
    }

    @Override
    public void onSelectedStroage(int position) {

    }

    @Override
    public void onSelectCamera(int position) {

    }
}
